/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> ret;
        if(root == nullptr)
            return ret;
        
        queue<TreeNode*> que;
        bool flag = false;  // 奇数是 false; 偶数是 true
        if(root != nullptr)
            que.push(root);
        while(!que.empty())
        {
            vector<int> tmp;
            for(int i = que.size() - 1; i >= 0; i--)
            {
                TreeNode* t = que.front();  // 取出队头元素
                que.pop();                  // 出队列
                tmp.push_back(t->val);
                if(t->left)
                    que.push(t->left);
                if(t->right)
                    que.push(t->right);
            }
            if(flag)    // 偶数行就反转后，再插入 ret
            { 
                reverse(tmp.begin(), tmp.end());
                flag = false;   // 偶数行完毕后，置为 false
            }
            else
            {
                flag = true;    // 奇数行完毕后，置为 true
            }
            ret.push_back(tmp);             
        }

        return ret;
    }
};